package com.polaris.live.dialog

import android.content.Context
import android.graphics.Paint
import android.os.CountDownTimer
import android.view.View
import com.blankj.utilcode.util.ColorUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.core.CenterPopupView
import com.lxj.xpopup.util.XPopupUtils
import com.polaris.live.R
import com.polaris.live.common.constant.PagConst.BG_LIGHT_BMP_PAG
import com.polaris.live.common.constant.PagConst.RECHARGE_NAME
import com.polaris.live.common.ext.convertArabicDigitsToNormal
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.ext.sp
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.AppCodeUtils
import com.polaris.live.common.util.DateUtils
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.TrackEventConst
import com.polaris.live.constant.TrackEventConst.EVENT_RECHARGE_TODAY_PV
import com.polaris.live.constant.TrackEventConst.RECHARGE_TODAY_PAGE
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.DialogTodayGratiaBinding
import com.polaris.live.manager.GooglePayManager
import com.polaris.live.manager.LiveStateManager
import com.polaris.live.resp.back_resp.PayerRechargePriceListVo
import com.polaris.live.utils.TrackHelper
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.utils.image.ImageUtils
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.libpag.PAGFile
import org.libpag.PAGText

/**
 * 今日特惠
 *
 * @author Created by 半仙 on 2023/10/17/017 15:08
 */
class TodayGratiaDialog(
    context: Context,
    private val todayRechargeResp: List<PayerRechargePriceListVo>,
    private val onRechargeOk: ((type: Boolean) -> Unit)? = null,
    private val onCountDown: ((unit: Boolean) -> Unit)? = null,
) : CenterPopupView(context) {

    private var time: TimeCount? = null

    private lateinit var mBinding: DialogTodayGratiaBinding

    private var rechargeOk = false

    private var mRechargeJob: Job? = null

    override fun getImplLayoutId(): Int {
        return R.layout.dialog_today_gratia
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = DialogTodayGratiaBinding.bind(popupImplView)
        var startTime: Long? = null
        todayRechargeResp.forEach {
            startTime = it.rewardsExp
        }
        time = startTime?.let { TimeCount(it, 1000) }
        time?.start()
        val item = todayRechargeResp[0]

        mBinding.apply {
            notPriceText.paintFlags = notPriceText.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
            if (item.coin == 0L) {
                notPriceText.visibility = View.GONE
            } else {
                notPriceText.visibility = View.VISIBLE
                notPriceText.text = "${item.coin}"
            }

            if (item.giveCoin == 0L) {
                okPriceText.visibility = View.GONE
                notPriceText.visibility = View.GONE
            } else {
                okPriceText.visibility = View.VISIBLE
                okPriceText.text = "+${item.giveCoin}"
            }
            rechargeItemText.text = "${item.coin + item.giveCoin}"
            okPriceText.text = "+${item.giveCoin}"
            Glide.with(context).load(ImageUtils.imgPath(item.icon)).into(ivCoin)
        }
        if (item.extraReward != null) {
            mBinding.reLlEx.visibility = VISIBLE
            mBinding.jiaTv.visibility = VISIBLE
            mBinding.rechargeItemExGratiaText.visibility = VISIBLE
            mBinding.rechargeExCount.visibility = VISIBLE
            mBinding.yuanLl.setBackgroundResource(R.drawable.r8_back_ffffff)
            mBinding.rechargeExCount.text = "X${item.extraReward.number}"
            Glide.with(context).load(ImageUtils.imgPath(item.extraReward.icon)).into(mBinding.ivCoinEx)
            mBinding.rechargeItemTextEx.text = "${item.extraReward.coin}"
        }

        mBinding.icClose.setOnSingleClickListener {
            dismiss()
        }

        mBinding.pagBack.apply {
            path = BG_LIGHT_BMP_PAG
            setRepeatCount(-1)
            play()
        }

        mBinding.pagBottom.setOnSingleClickListener {
            TrackHelper.postTrack(RECHARGE_TODAY_PAGE, TrackEventConst.EVENT_TOPUP_PC)
            ViewUtils.getTopActivity(context)?.apply {
                GooglePayManager.buyShow(this,
                    item.priceId,
                    UserConst.From.UNKNOWN,
                    item.payerRechargeRewardsType,
                    price = item.price,
                    onSuccess = {
                        rechargeOk = true
                        dismiss()
                    })
            }
        }
        mRechargeJob = CoroutineScopeManager.ioScope.launch {
            val filePath = FileUtils.getAssetsToFilePag(RECHARGE_NAME)
            val pagFile = PAGFile.Load(filePath)

            val pagText = PAGText().apply {
                text = "$" + item.price
                fillColor = ColorUtils.getColor(R.color.white)
                fontSize = 18.sp.toFloat()
                justification = PAGText.Justification.Center
            }
            pagFile.replaceText(0, pagText)
            withContext(CoroutineScopeManager.mainDispatcher) {
                mBinding.pagBottom.apply {
                    composition = pagFile
                    setRepeatCount(-1)
                    play()
                }
            }
        }
    }

    override fun onShow() {
        LiveStateManager.updateRechargeState(true)
        LiveStateManager.updataFastRechargeState(true)

        TrackHelper.postTrack(
            RECHARGE_TODAY_PAGE,
            EVENT_RECHARGE_TODAY_PV,
            TrackEventConst.TRACK_DIALOG,
            mutableMapOf("sourcePage" to TrackHelper.rechargePageMap(context))
        )
        super.onShow()
    }

    override fun getMaxWidth(): Int {
        if (popupInfo == null) return 0
        return if (popupInfo.maxWidth == 0) (XPopupUtils.getAppWidth(context) * 1f).toInt() else popupInfo.maxWidth
    }

    override fun onDismiss() {
        if (time != null) {
            time?.cancel()
            time = null
        }
        mRechargeJob?.cancel()
        mRechargeJob = null
        LiveStateManager.updataFastRechargeState(false)
        LiveStateManager.updateRechargeState(false)
        onRechargeOk?.invoke(rechargeOk)
        super.onDismiss()
    }

    override fun onDestroy() {
        LiveStateManager.updateRechargeState(false)
        LiveStateManager.updataFastRechargeState(false)
        super.onDestroy()
    }

    override fun onBackPressed(): Boolean {
        LiveStateManager.updateRechargeState(false)
        LiveStateManager.updataFastRechargeState(false)
        return super.onBackPressed()
    }

    internal inner class TimeCount(millisInFuture: Long, countDownInterval: Long) :
        CountDownTimer(millisInFuture, countDownInterval) {

        override fun onTick(millisUntilFinished: Long) {
            val time = DateUtils.formatDuration(millisUntilFinished).convertArabicDigitsToNormal()
            val split = time.split(":")
            if (AppCodeUtils.isAR()) {
                mBinding.timeHour.text = split[2]
                mBinding.timeMinute.text = split[1]
                mBinding.timeSecond.text = split[0]
            } else {
                mBinding.timeHour.text = split[0]
                mBinding.timeMinute.text = split[1]
                mBinding.timeSecond.text = split[2]
            }
        }

        override fun onFinish() {
            onCountDown?.invoke(true)
            dismiss()
        }
    }
}